package com.keson.guard.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.keson.guard.MainActivity;
import com.keson.guard.R;
import com.keson.guard.util.Cache;
import com.keson.guard.util.CmdUtil;
import com.keson.guard.util.DownLoadUtil;
import com.keson.guard.util.MqttClientUtil;
import com.keson.guard.util.UICheckUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.io.IOException;

import static android.content.ContentValues.TAG;

public class GuardService extends Service {
    private boolean isDownLoading = false;
    public GuardService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MqttClientUtil.subscribeTopic("guard", 2);
                while (true){
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(UICheckUtil.isApkInstalled(GuardService.this,"com.keson.eq")){
                        if(!Cache.isSetting&& !UICheckUtil.isServiceStarted(GuardService.this,"com.keson.eq")){
                            CmdUtil.execRootCmd("am start -n com.keson.eq/.StartActivity");
                        }
                    }else{
                        System.out.println("检测到应用不存在");
                        if(!isDownLoading){
                            isDownLoading = true;
                            String url = Build.MODEL.indexOf("3399")>-1?("http://47.94.80.3:8080/update/eqplayer3399.apk"):
                                         Build.MODEL.indexOf("328")>-1?("http://47.94.80.3:8080/update/eqplayer.apk"):
                                         Build.MODEL.indexOf("tml")>-1?("http://47.94.80.3:8080/update/eqplayer100c.apk"):
                                         Build.MODEL.indexOf("ZCT")>-1?("http://47.94.80.3:8080/update/eqplayerzed.apk"):
                                         Build.MODEL.indexOf("3588")>-1?("http://47.94.80.3:8080/update/eqplayer3588.apk"):"";
                            if(Build.MODEL.contains("3399")){

                            }
                            String fileName = "eqplayer.apk";
//                            String savePath = Environment.getExternalStorageDirectory().toString()+"/Download";
//                            try {
//                                DownLoadUtil.downLoadFromUrl(url,fileName,savePath);
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                            if(new File(Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer.apk").exists()){
//                                CmdUtil.execRootCmd("pm install -r " + Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer.apk");
////                                CmdUtil.execRootCmd("pm install -r " + Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer3399.apk");
////                                Intent intent = getPackageManager().getLaunchIntentForPackage("com.keson.eq");
////                                if (intent != null) {
////                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////                                    startActivity(intent);
////                                }
//                                CmdUtil.execRootCmd("am start -n com.keson.eq/.StartActivity");
//                                CmdUtil.execRootCmd("am force-stop com.keson.eq");
//                                CmdUtil.execRootCmd("am start -n com.keson.eq/.StartActivity");
//                            }
//                            isDownLoading = false;
                            File apkFile = new File(Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName);
                            if(apkFile.exists()){
                                apkFile.delete();
                            }
                            String mSavePath = Environment.getExternalStorageDirectory().toString() + "/Download";
                            BaseDownloadTask task = FileDownloader.getImpl().create(url);
                            task.setPath(mSavePath+"/"+fileName)
                                    .setForceReDownload(true)
                                    .setListener(new FileDownloadListener(){
                                        @Override
                                        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                        }

                                        @Override
                                        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                                            System.out.println("正在下载 "+soFarBytes+"/"+totalBytes+"  "+task.getSpeed()+"kb/s");
                                        }

                                        @Override
                                        protected void completed(BaseDownloadTask task) {
                                            if(new File(Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer.apk").exists()){
                                                CmdUtil.execRootCmd("pm install -r " + Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer.apk");
                                                CmdUtil.execRootCmd("am start -n com.keson.eq/.StartActivity");
                                                CmdUtil.execRootCmd("am force-stop com.keson.eq");
                                                CmdUtil.execRootCmd("am start -n com.keson.eq/.StartActivity");
                                                System.out.println("预警软件重装完毕");
                                            }
                                            isDownLoading = false;
                                        }

                                        @Override
                                        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                                        }

                                        @Override
                                        protected void error(BaseDownloadTask task, Throwable e) {
                                            System.out.println("错误，10秒后重新尝试下载");
                                            try {
                                                Thread.sleep(10000);
                                            } catch (InterruptedException e1) {
                                                e1.printStackTrace();
                                            }
                                            task.reuse();
                                            task.start();
                                        }

                                        @Override
                                        protected void warn(BaseDownloadTask task) {

                                        }
                                    }).start();
                        }else{
                            System.out.println("正在下载");
                        }
                    }
                }
            }
        }).start();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //https://blog.csdn.net/The_king_of_Asia/article/details/104036915
            //设置点击跳转
            Context context=getApplicationContext();
            Intent intent = new Intent(context, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            String id = "1";
            String name = "channel_name_1";
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
                mChannel.setSound(null, null);
                notificationManager.createNotificationChannel(mChannel);
                notification = new Notification.Builder(context)
                        .setChannelId(id)
                        .setContentTitle(context.getResources().getString(R.string.app_name))
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(false)// 设置这个标志当用户单击面板就可以让通知将自动取消
                        .setOngoing(true)// true，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                        .setSmallIcon(R.drawable.ic_launcher_background).build();
            } else {
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                        .setContentTitle(context.getResources().getString(R.string.app_name))
                        .setContentIntent(pendingIntent)
                        .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                        .setAutoCancel(false)// 设置这个标志当用户单击面板就可以让通知将自动取消
                        .setOngoing(true)// true，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                        .setSmallIcon(R.drawable.ic_launcher_background);
                notification = notificationBuilder.build();
            }
            startForeground(1, notification);

            Log.d(TAG,"service onCreate");
        }
    }
}
